package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.model.entity.Category;
import com.itheima.reggie.model.entity.Dish;
import com.itheima.reggie.model.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类 删除之前需要判断当前分类是否关联菜品和套餐
     * @param ids
     */
    @Override
    public void remove(Long ids){

        //查询当前分类是否关联菜品，若关联，则抛出一个业务异常
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper();
        //添加查询条件，根据category的id 查询
        dishWrapper.eq(Dish::getCategoryId,ids);
        //得到查询返回的记录数
        int count1 = dishService.count(dishWrapper);
        if (count1 > 0){
            //当前分类已关联菜品，抛出一个业务异常
            throw new CustomException("当前分类已关联菜品，请先解除关联");
        }


        //查询当前分类是否关联套餐，若关联，则抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper();
        setmealWrapper.eq(Setmeal::getCategoryId,ids);
        int count2 = setmealService.count(setmealWrapper);
        if (count2 > 0){
            //当前分类已关联套餐，抛出一个业务异常
            throw new CustomException("当前分类已关联套餐，请先解除关联");
        }


        //若两次查询都没有关联，则删除该分类
        super.removeById(ids);
    }
}
